package com;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * sql 注入
 * 
 * @author lenovo
 * @date 2020年8月7日 @time 上午8:28:26
 */
public class JDBC_04_PreparedStatement {

	public static void main(String[] args) {
//		login("root", "root");
		login("'or 1=1 or 1>'", "11");
//		where username = '1=1' and password = '11'
//		where username = "or 1=1 or 1='1' and password = '11'"
	}

	public static void login(String username, String password) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			// 1 加载驱动
			Class.forName("com.mysql.jdbc.Driver");

			// 2 数据库连接
			// jdbc:mysql://IP地址 : 端口号 / 数据库
			connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/day_03", "root", "root");

			// 3 语句传输对象

			// 使用通配符 ? 替代值
			String sql = "select * from t_user where username = ? and password = ?";
			preparedStatement = connection.prepareStatement(sql);

			// 设置第一个 ? 的值
			preparedStatement.setString(1, username);
			preparedStatement.setString(2, password);

			// 4 接收结果集
			resultSet = preparedStatement.executeQuery(sql);

			if (resultSet.next()) {
				System.out.println("登录成功 ,欢迎:" + resultSet.getString("nickname"));

			} else {
				System.out.println("登录失败 , 用户名或密码错误");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (resultSet != null) {
					resultSet.close();
				}
				if (preparedStatement != null) {
					preparedStatement.close();
				}
				if (connection != null) {
					connection.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
}
